/*
 * Gsoft开发框架
 * Copyright 2015-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.itcncp.ipaybox.server.resolver;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import com.itcncp.common.ipaybox.BoxConstants;
import com.itcncp.common.ipaybox.model.BoxData;
import com.itcncp.common.ipaybox.model.BoxRequest;
import com.itcncp.common.ipaybox.model.BoxResponse;
import com.itcncp.common.util.DateUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.itcncp.ipaybox.trans.dubbo.service.DubboService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * 被扫
 * 
 * @author LiuPeng
 * @date 2017年12月19日
 * 
 */
@Component
public class Box1015Resolver implements MsgResolverAdapter {

	private ExecutorService executorService = Executors.newFixedThreadPool(10);

	@Resource(name = "itcsApp")
	private DubboService itcsApp;

	@Override
	public boolean support(BoxRequest boxRequest) {
		return "1015".equals(boxRequest.getMessgeType());
	}

	@Override
	public void resolve(ChannelHandlerContext channelHandlerContext, BoxRequest boxRequest) {
		BoxResponse boxResponse = new BoxResponse();
		BoxData data = boxRequest.getData();
		// 返回应答信息
		boxResponse.setKey(data.getDeviceId());
		boxResponse.setMessgeType("2015");
		BoxData responseData = new BoxData();
		responseData.setDeviceId(data.getDeviceId());
		responseData.setTransacSeq(boxRequest.getData().getTransacSeq());
		// 应答时间
		responseData.setReplyTime( DateUtils.getToday("yyyy-MM-dd HH:mm:ss"));
		boxResponse.setData(responseData);
		ByteBuf byteBuf = Unpooled.wrappedBuffer(JSON.toJSONString(boxResponse).getBytes( BoxConstants.CHARSET_UTF8));
		channelHandlerContext.writeAndFlush(byteBuf);

		// 将被扫请求发送到app
		Send2AppThread appThread = new Send2AppThread(itcsApp, channelHandlerContext, boxRequest);
		executorService.execute(appThread);
	}

}
